package com.nfl.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;


public class UploadFile {

    //[start] upload_sendFile
    final static String ENCORDING="UTF-8";
    final static String lineEnd = "\r\n";

    public static  boolean upload_sendFile(HttpURLConnection conn,String filepath) throws Exception {

        File file = new File(filepath);
        if(!file.exists() || !file.isFile()){
            return false;
        }
//    	 String boundary = "---------------------------7db1c523809b2";//+java.util.UUID.randomUUID().toString();//  
        String boundary = "---------------------------lituploadfile"+java.util.UUID.randomUUID().toString();





        // 用来开启连接   
        StringBuilder sb = new StringBuilder();
        // 用来拼装请求  
  
        /*// username字段 
        sb.append("--" + boundary + lineEnd); 
        sb.append("Content-Disposition: form-data; name=\"username\"" + lineEnd); 
        sb.append(lineEnd); 
        sb.append(username + lineEnd); 
 
        // password字段 
        sb.append("--" + boundary + lineEnd); 
        sb.append("Content-Disposition: form-data; name=\"password\"" + lineEnd); 
        sb.append(lineEnd); 
        sb.append(password + lineEnd);*/

        // 文件部分  
        sb.append("--" + boundary + lineEnd);
        sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + filepath + "\"" + lineEnd);
        sb.append("Content-Type: image/jpg" + lineEnd);
        sb.append(lineEnd);

        // 将开头和结尾部分转为字节数组，因为设置Content-Type时长度是字节长度  
        byte[] before = sb.toString().getBytes(ENCORDING);
        byte[] after = (lineEnd+"--" + boundary + "--"+lineEnd).getBytes(ENCORDING);

        // 打开连接, 设置请求头  

        conn.setConnectTimeout(10000);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        conn.setRequestProperty("Content-Length", before.length + file.length() + after.length + "");

//        conn.setDoOutput(true);  
//        conn.setDoInput(true);  

        // 获取输入输出流  
        OutputStream out = conn.getOutputStream();
        try{
            // 将开头部分写出
            out.write(before);

            // 写出文件数据
            int len;
            byte[] buf = new byte[1024*5];
            FileInputStream fis = new FileInputStream(file);
            try{
                while ((len = fis.read(buf)) != -1)
                    out.write(buf, 0, len);
            }finally{
                fis.close();
            }
            // 将结尾部分写出
            out.write(after);
            out.flush();
        }finally{
            out.close();
        }
        return true;
    }
    //[end]2

}
